<template>
  <view class="edit-period-container">
    <!-- 使用uview的导航栏组件 -->
    <up-navbar bgColor="#ff6700" title="编辑营员" titleStyle="color: #ffffff; font-size: 36rpx; font-weight: bold"
      :safeAreaInsetTop="true" height="88rpx">
      <template #left>
        <view class="nav-left" @click="goBack">
          <up-icon name="arrow-left" size="24" color="#fff"></up-icon>
          <text class="nav-back-text">返回</text>
        </view>
      </template>
    </up-navbar>

    <!-- 表单区域 -->
    <view class="form-container">
		
			<!-- 安全距离块 -->
			<view class="safe-area" :style="{ height: (GM_STATUS_BAR_HEIGHT + 80) + 'rpx' }"></view>
			
      <!-- 基本信息卡片 -->
      <view class="info-card">
				
				<view class="flex-row-start u-m-b-30" style="align-items: flex-start;">
					<!-- 头像区域 -->
					<view class="avatar-container flex-column-center" @click="uploadAvatar" v-if="formData.photo">
					  <image class="avatar" :src="formData.photo" mode="aspectFill"></image>
						<view class="close-icon" @click="formData.photo = ''">
							<u-icon name="close" color="#fff" size="15"></u-icon>
						</view>
					</view>
					<view class="avatar-container flex-column-center" @click="uploadAvatar" v-else>
						<u-icon name="plus" color="#999"></u-icon>
						<view class="color-999 u-font-24 u-m-t-20">添加头像</view>
					</view>
					<view class="flex-1 u-m-l-20">
						<!-- 个人信息输入项 -->
						<view class="form-item">
						  <text class="label">营员姓名</text>
						</view>
						<view class="form-inp">
							<u-input class="input" v-model="formData.name" placeholder="请输入营员姓名" placeholderStyle="color: #999"
								border="none" />
						</view>
						
						<view class="form-item u-m-t-10">
						  <text class="label">身份证号</text>
						</view>
						<view class="form-inp">
						  <u-input class="input" v-model="formData.idCard" placeholder="请输入营员身份证号" placeholderStyle="color: #999"
						    border="none" type="idcard" maxlength="18" />
						</view>
					</view>
				</view>

        <view class="form-item">
          <text class="label">营员特殊备注</text>
        </view>
				<view class="form-inp">
          <up-input class="input" v-model="formData.remark" placeholder="请输入营员备注" placeholderStyle="color: #999"
            border="none" />
				</view>

        <view class="form-item u-m-t-20">
          <text class="label">参营物品收货地址</text>
        </view>
				<view class="flex-row-start">
					<view class="flex-column-center form-plus u-m-r-20 u-m-t-10" v-if="!cadetId">
						<u-icon name="plus" color="#999"></u-icon>
					</view>
					<view class="form-inp flex-1">
					  <up-input class="input" v-model="formData.address" placeholder="参营物品收货地址" placeholderStyle="color: #999"
					    border="none" />
					</view>
				</view>

        <!-- <view class="form-item">
          <text class="label">学校</text>
          <up-input class="input" v-model="formData.school" placeholder="请输入学校名称" placeholderStyle="color: #999"
            border="none" />
        </view>

        <view class="form-item">
          <text class="label">年龄</text>
          <up-input class="input" v-model.number="formData.age" placeholder="请输入年龄" placeholderStyle="color: #999"
            border="none" type="number" v-if="mode === 'edit'" disabled />
          <up-input class="input" v-model.number="formData.age" placeholder="请输入年龄" placeholderStyle="color: #999"
            border="none" type="number" v-else />

        </view>

        <view class="add-idcard-btn" @click="showIdCardRecognition">
          <up-icon name="camera" size="20" color="#ff6700"></up-icon>
          <text>身份证识别信息（可选）</text>
        </view> -->
      </view>

      <!-- 校外机构卡片 -->
      <!-- <view class="info-card mt-20">
        <view class="card-title">校外机构</view>

        <view class="institution-list">
          <view class="institution-item" v-for="(item, index) in formData.institutions" :key="index">
            <up-input class="institution-input" v-model="item.institution" placeholder="请输入机构名称"
              placeholderStyle="color: #999" border="none" />
            <view class="operation-group">
              <text class="delete-btn" @click="deleteInstitution(index)">删除</text>
            </view>
          </view>
        </view>

        <view class="add-institution-btn" @click="addInstitution">
          <up-icon name="plus" size="20" color="#ff6700"></up-icon>
          <text>添加机构</text>
        </view>
      </view> -->

			<view class="remark-input u-m-t-50">
				纤程旅行将根据您授权并使用您的信息，具体请参阅<text class="color-blue">《隐私信息保护政策》</text>
      </view>

      <!-- 提交按钮 -->
      <!-- <view class="submit-btn-container">
        <up-button @click="submitForm" class="submit-btn" type="primary" shape="circle" size="default">
          提交
        </up-button>
      </view> -->
    </view>
		
		<!-- 底部操作按钮 -->
		<view class="bottom-actions">
		  <button class="add-btn goback-btn" @click="goBack" plain>返回</button>
		  <button class="add-btn add-cadet-btn" @click="deleteFn">删除</button>
		  <button class="add-btn add-guardian-btn" @click="submitForm">保存</button>
		</view>

    <!-- 注释信息区域 -->
    <!-- <view class="notes-container">
      <view class="padding bg-white">
        <view class="text-left padding">*注释</view>
        <view class="text-left padding">根据少儿姓名、性别我们将更好地安排出行服务</view>
        <view class="text-left padding">根据少儿姓名、身份证号购买意外保险</view>
        <view class="text-left padding">根据少儿身份证号用于计算少儿年龄</view>
        <view class="text-left padding">根据居住地信息为你推荐更合适的集合点</view>
        <view class="text-left padding">根据年龄、性别、位置推荐合适的研学营给您</view>
        <view class="text-left padding">根据家长身份及联系方式，方便团队与您沟通和联系</view>
        <view class="text-left padding">添加监护人，更好与你沟通少儿的参营情况</view>
      </view>
    </view> -->

    <!-- 底部选择模态框 -->
    <up-popup v-model="showModal" mode="bottom" :round="16" :overlay="true" @close="hideModal">
      <view class="modal-container">
        <view class="modal-header">
          <text class="cancel-btn" @click="hideModal">取消</text>
          <text class="confirm-btn" @click="confirmSelection">确定</text>
        </view>

        <view class="modal-content">
          <view class="vertical-box">
            <scroll-view class="vertical-nav" scroll-y scroll-with-animation :scroll-top="verticalNavTop"
              style="height:calc(100vh - 400rpx)">
              <view class="cu-item" :class="{ 'text-orange cur': index === tabCur }"
                v-for="(item, index) in categoryList" :key="index" @click="tabSelect(index)">
                {{ item.name }}
              </view>
            </scroll-view>

            <scroll-view class="vertical-main" scroll-y scroll-with-animation style="height:calc(100vh - 400rpx)"
              :scroll-into-view="`main-${mainCur}`" @scroll="handleScroll">
              <up-checkbox-group @change="checkboxChange" :name="saveType">
                <view class="padding-top padding-lr" v-for="(item, index) in categoryList" :key="index"
                  :id="`main-${index}`">
                  <view class="cu-bar solid-bottom bg-white">
                    <view class="action">
                      <text class="cu-icon-title text-orange"></text>{{ item.name }}
                    </view>
                  </view>
                  <view class="cu-list menu-avatar">
                    <view class="cu-form-group" v-for="ite in item.maxlist" :key="ite.text">
                      <view class="title">{{ ite.text }}</view>
                      <up-checkbox :value="ite.text" :checked="ite.checked" shape="circle"
                        activeColor="#ff6700"></up-checkbox>
                    </view>
                  </view>
                </view>
              </up-checkbox-group>
            </scroll-view>
          </view>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script>
import { useUserStore } from '@/store';
import { request } from '@/utils/request';

export default {
  data() {
    return {
      // 表单数据
      formData: {
        name: '',
        idCard: '',
        address: '',
        school: '',
        age: 0, // 修改为数字类型
        photo: '',
        institutions: [{ institution: '' }]
      },

      // 其他状态
      showModal: false,
      tabCur: 0,
      mainCur: 0,
      verticalNavTop: 0,
      saveType: '',
      defaultAvatar: '/static/logo.png',

      // 页面ID和模式
      cadetId: '',
      mode: 'add',
			GM_STATUS_BAR_HEIGHT: uni.getStorageSync('GM_STATUS_BAR_HEIGHT'),
    };
  },

  onLoad(options) {
    // 获取页面参数
    if (options.id) {
      console.log('编辑营员', options.id);
      this.cadetId = options.id;
      this.mode = 'edit';
      this.loadCadetData();
    } else if (options.mode) {
      console.log('添加营员', options.mode);
      this.mode = options.mode;
    }
  },

  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack({
        delta: 1
      });
    },

    // 加载营员数据
    async loadCadetData() {
      try {
        // 显示加载提示
        uni.showLoading({
          title: '加载中...'
        });

        // 使用request.js发送GET请求到'/campers/{id}'接口
        const response = await request({
          url: `/campers/${this.cadetId}`,
          method: 'GET'
        });

        // 隐藏加载提示
        uni.hideLoading();
        console.log('获取营员数据成功', response.data);
        // 处理响应结果
        if (response && response.data) {
          const cadetData = response.data;

          // 更新表单数据 - 修复institution数据处理逻辑，防止null或undefined值导致的迭代错误
          this.formData = {
            name: cadetData.name || '',
            idCard: cadetData.idCard || '',
            address: cadetData.address || '',
            school: cadetData.school || '',
            age: cadetData.age || 0,
            photo: cadetData.photo || '',
            // 安全地处理institution数据，确保它是一个数组
            institutions: Array.isArray(cadetData.institutions) && cadetData.institutions.length > 0
              ? cadetData.institutions.map(item => ({ institution: item && item.institution ? item.institution : '' }))
              : [{ institution: '' }]
          };
        } else {
          uni.showToast({
            title: '加载数据失败',
            icon: 'none'
          });
        }
      } catch (error) {
        // 隐藏加载提示
        uni.hideLoading();

        console.error('加载营员数据失败:', error);
        uni.showToast({
          title: '加载数据失败，请重试',
          icon: 'none'
        });
      }
    },

    // 上传头像
    uploadAvatar() {
      const token = uni.getStorageSync('accessToken');
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => { // 这里改成箭头函数
          const tempFilePath = res.tempFilePaths[0];
          console.log('选择的图片路径:', tempFilePath);
          this.formData.photo = tempFilePath;
          uni.uploadFile({
            url: 'https://abc.qctrips.cn/local-file/upload',
            filePath: tempFilePath,
            name: 'file',
            header: { 'Authorization': token },
          }).then(res => {

            console.log('上传成功：', res);
            const data = JSON.parse(res.data);
            this.formData.photo = data.data.url;
          })
        },
        fail: (err) => {
          console.error('选择图片失败:', err);
        }
      });
    },

    // 显示身份证识别
    showIdCardRecognition() {
      uni.showToast({
        title: '身份证识别功能待实现',
        icon: 'none'
      });
    },

    // 添加机构
    addInstitution() {
      this.formData.institutions.push({ institution: '' });
    },

    // 删除机构
    deleteInstitution(index) {
      if (this.formData.institutions.length > 1) {
        this.formData.institutions.splice(index, 1);
      } else {
        uni.showToast({
          title: '至少保留一个机构',
          icon: 'none'
        });
      }
    },
    // 根据身份证号计算年龄
    getAgeByIdCard(idCard) {
      if (!idCard || idCard.length !== 18) {
        return 0;
      }

      // 从身份证号中提取出生年月日
      const birthYear = parseInt(idCard.substring(6, 10));
      const birthMonth = parseInt(idCard.substring(10, 12));
      const birthDay = parseInt(idCard.substring(12, 14));

      // 获取当前日期
      const now = new Date();
      const currentYear = now.getFullYear();
      const currentMonth = now.getMonth() + 1;
      const currentDay = now.getDate();

      // 计算年龄
      let age = currentYear - birthYear;

      // 如果当前月份小于出生月份，或者月份相同但日期小于出生日期，则年龄减1
      if (currentMonth < birthMonth || (currentMonth === birthMonth && currentDay < birthDay)) {
        age--;
      }

      return age;
    },

    // 提交表单 - 新增时使用POST /campers，编辑时使用PUT /campers/{id}
    async submitForm() {
      // 表单验证
      if (!this.formData.name) {
        return uni.showToast({ title: '请输入姓名', icon: 'none' });
      }

      if (!this.formData.idCard) {
        return uni.showToast({ title: '请输入身份证号', icon: 'none' });
      }

      try {
        // 根据身份证号计算年龄
        const age = this.getAgeByIdCard(this.formData.idCard);

        // 准备提交的数据 - 修复institution数据处理逻辑
        const submitData = {
          name: this.formData.name,
          age: age,
          idCard: this.formData.idCard,
          address: this.formData.address,
          school: this.formData.school,
          // 安全地处理institutions数组
          institutions: Array.isArray(this.formData.institutions)
            ? this.formData.institutions.map(item => ({ institution: item && item.institution ? item.institution : '' }))
            : [{ institution: '' }],
          photo: this.formData.photo
        };

        // 显示加载提示
        uni.showLoading({
          title: '提交中...'
        });

        let response;
        // 根据模式选择不同的请求方式和接口
        if (this.mode === 'edit' && this.cadetId) {
          // 编辑模式：使用PUT /campers/{id}接口
          response = await request(
            {
              url: `/campers/${this.cadetId}`,
              method: 'PUT',
              data: submitData
            }
          );
        } else {
          // 新增模式：使用POST /campers接口
          response = await request(
            {
              url: '/campers',
              method: 'POST',
              data: submitData
            }
          );
        }

        // 隐藏加载提示
        uni.hideLoading();

        // 处理响应结果
        if (response && response.code === 200) {
          uni.showToast({
            title: this.mode === 'add' ? '添加成功' : '编辑成功',
            icon: 'success',
            duration: 2000,
            success: () => {
              setTimeout(() => {
                //给上个页面发个消息，通知父页面刷新
                uni.$emit('refreshOrder');
                this.goBack();
              }, 1500);
            }
          });
        } else {
          uni.showToast({
            title: response && response.code === 200 ? response.message : '提交失败',
            icon: 'none'
          });
        }
      } catch (error) {
        // 隐藏加载提示
        uni.hideLoading();

        console.error('提交表单失败:', error);
        uni.showToast({
          title: '提交失败，请重试',
          icon: 'none'
        });
      }
    },

    // 显示选择模态框
    showSelectionModal(type) {
      this.saveType = type;
      this.showModal = true;
    },

    // 隐藏模态框
    hideModal() {
      this.showModal = false;
    },

    // 确认选择
    confirmSelection() {
      // 处理选择结果
      this.hideModal();
    },

    // 切换标签
    tabSelect(index) {
      this.tabCur = index;
      this.mainCur = index;
      this.verticalNavTop = index * 50;
    },

    // 处理滚动
    handleScroll(e) {
      // 处理滚动逻辑
      const scrollTop = e.detail.scrollTop;
      // 可以根据滚动位置更新tabCur
    },

    // 处理复选框变化
    checkboxChange(e) {
      console.log('复选框变化:', e);
      // 处理复选框选择结果
    }
  }
};
</script>

<style scoped>
.edit-period-container {
  min-height: 100vh;
  background-color: #f8f8f8;
}

/* uview导航栏相关样式 */
.nav-left {
  display: flex;
  align-items: center;
  color: #fff;
}

.nav-back-text {
  color: #fff;
  margin-left: 8rpx;
  font-size: 30rpx;
}

/* 表单区域 */
.form-container {
  padding: 30rpx;
  /* 为导航栏留出空间 */
}

/* 信息卡片 */
.info-card {
}

.mt-20 {
  margin-top: 20rpx;
}

/* 头像区域 */
.avatar-container {
	background: #eee;
	border-radius: 4rpx;
	overflow: hidden;
	height: 250rpx;
	width: 250rpx;
	position: relative;
}
.close-icon{
	position: absolute;
	background: rgba(0,0,0,.6);
	right: 0;
	top: 0;
	padding: 6rpx;
}

.avatar {
  width: 100%;
  height: 100%;
}

.edit-avatar {
  color: #ff6700;
  font-size: 28rpx;
}

/* 表单项 */
.form-item {
	height: 46rpx;
}
.form-inp{
	border: 2rpx solid #eee;
	padding: 8rpx 14rpx;
	background: #f5f5f5;
	border-radius: 4rpx;
	margin-top: 10rpx;
}
.form-plus{
	background: #eee;
	border-radius: 4rpx;
	overflow: hidden;
	height: 68rpx;
	width: 68rpx;
}

.label {
  color: #999;
  font-size: 24rpx;
}

.input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

/* 身份证识别按钮 */
.add-idcard-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
  margin-top: 20rpx;
  color: #ff6700;
  font-size: 28rpx;
}

/* 校外机构相关 */
.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.institution-list {
  margin-bottom: 20rpx;
}

.institution-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.institution-input {
  flex: 1;
  font-size: 28rpx;
}

.operation-group {
  margin-left: 20rpx;
}

.delete-btn {
  color: #ff4757;
  font-size: 28rpx;
}

.add-institution-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
  color: #ff6700;
  font-size: 28rpx;
  border-top: 1rpx dashed #eee;
  margin-top: 10rpx;
}

/* 备注信息 */
.remark-input {
  font-size: 24rpx;
  color: #666;
  line-height: 1.6;
}

/* 提交按钮 */
.submit-btn-container {
  margin-top: 40rpx;
  padding: 0 20rpx;
}

.submit-btn {
  background-color: #ff6700 !important;
  color: #fff !important;
  font-size: 32rpx;
  height: 96rpx;
}

/* 注释信息 */
.notes-container {
  margin-top: 20rpx;
  margin-bottom: 120rpx;
  /* 为底部留出空间 */
}

.notes-container .padding {
  padding: 15rpx 30rpx;
  font-size: 24rpx;
  color: #666;
  line-height: 1.8;
}

/* 模态框样式 */
.modal-container {
  background-color: #fff;
  border-radius: 16rpx 16rpx 0 0;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #eee;
}

.cancel-btn {
  color: #666;
  font-size: 32rpx;
}

.confirm-btn {
  color: #ff6700;
  font-size: 32rpx;
  font-weight: bold;
}

.modal-content {
  padding: 20rpx;
}

.vertical-box {
  display: flex;
  height: calc(100vh - 400rpx);
}

.vertical-nav {
  width: 200rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
}

.cu-item {
  padding: 20rpx;
  font-size: 28rpx;
  color: #333;
  text-align: center;
}

.cu-item.text-orange {
  color: #ff6700;
}

.cu-item.cur {
  background-color: #fff;
  border-left: 4rpx solid #ff6700;
}

.vertical-main {
  flex: 1;
  margin-left: 20rpx;
}

.cu-bar {
  padding: 15rpx 0;
  font-size: 28rpx;
}

.cu-list {
  margin-top: 10rpx;
}

.cu-form-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.cu-form-group .title {
  font-size: 28rpx;
  color: #333;
}

/* 底部操作按钮 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 30rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  display: flex;
  gap: 30rpx;
	justify-content: space-between;
	font-size: 28rpx;
	padding-bottom: calc(contant(safe-area-inset-bottom) + 0rpx);
	padding-bottom: calc(env(safe-area-inset-bottom) + 0rpx);
}

.add-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 16rpx;
  font-size: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
}

.add-cadet-btn {
  background-color: #ff6700;
  color: #fff;
}

.add-guardian-btn {
  background-color: #ff6700;
  color: #fff;
}

.goback-btn{
	border: 2rpx solid #ff6700;
	color: #ff6700;
}
</style>